<template>
    <div class="common_page" :style="{ background: this.detail.style.backColor }">
        <div
            class="main_content"
            ref="mainContent"
            :style="{
                width: detail.style.position.w + 'px',
                height: detail.style.position.h + 'px',
                background: this.detail.style.backColor,
            }"
        >
            <div class="page_content" style="width: 100%">
                <div class="page_content_bottom">
                    <sysTable
                        :data="setTableData"
                        :columns="setTableColumns"
                        :curr-page="searchData.pageNum"
                        :total-page="pageTotal"
                        :page-size="searchData.pageSize"
                        @sizeChange="sizeChange"
                        @currentChange="currentChange"
                        @header-click="headerClick"
                    >
                        <template #unitEnergy_header>
                            <div class="header_with_unit">
                                <div style="line-height: 20px">单位能耗</div>
                                <div style="line-height: 20px">(能耗单位/小时)</div>
                            </div>
                        </template>
                    </sysTable>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import BaseView from './View';
import { mapGetters } from 'vuex';
import { equipentEnergyCharts, equipentEnergyList } from '@/views/energy/api/energy/energyMonitoring';
import * as echarts from 'echarts';
import { energyClassification } from '@/views/energy/api/energy/workShopEnergy';
import { getbuildingList, getEquipentList, getFloorList, getWorkShopList } from '@/views/energy/api/energy/equipmentEnergy';
import sysTable from '@/views/energy/components/SysTable/index.vue';
export default {
    name: 'view-warn',
    components: { sysTable },
    extends: BaseView,
    computed: {
        headerChange() {
            return this.detail.style.header;
        },
        ...mapGetters(['theme']),
        cssVars() {
            return {
                '--color': this.theme,
            };
        },
    },
    watch: {
        headerChange(newVal, oldVal) {
            // console.log("绑定数据变化了",newVal);
            if (oldVal) {
            }
        },
    },
    data() {
        return {
            searchData: {
                buildingId: '',
                workshopIds: null,
                floor: null,
                guid: null,
                deviceIds: null,
                classifyId: '',
                deviceName: '',
                date: [new Date(), new Date()],
                // type: 1,
                dateType: 1,
                pageSize: 10,
                pageNum: 1,
            },
            setTableData: [],
            pageTotal: 0,
            buildList: [],
            floorList: [],
            workShopList: [],
            dimensionList: [
                {
                    id: 1,
                    name: '时',
                },
                {
                    id: 2,
                    name: '日',
                },
                {
                    id: 3,
                    name: '月',
                },
            ],
            deviceList: [],
            classifyList: [],
            setTableColumns: [
                {
                    label: '设备名称',
                    prop: 'deviceName',
                    minWidth: '180',
                    align: 'center',
                    fixed: 'left',
                    showOverflowTooltip: true,
                },
                {
                    label: '总费用',
                    prop: 'equipmentConPrice',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
                {
                    label: '电量(kW·h)',
                    prop: 'powerConsumption',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
                {
                    label: '水量(m³)',
                    prop: 'waterConsumption',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
                {
                    label: '气量(m³)',
                    prop: 'gasConsumption',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
            ],
            pieEquipentL: [],
            pieEquipentY: [],
            barEquipentX: [],
            barEquipentY: [],
            chartsLoading: false,
            choiceDate0: '',
            dateComponentType: 'daterange', // daterange年月日， monthrange月
            pickerOptions: {
                // 设置不能选择的日期
                onPick: ({ maxDate, minDate }) => {
                    this.choiceDate0 = minDate.getTime();
                    if (maxDate) {
                        this.choiceDate0 = '';
                    }
                },
                disabledDate: (time) => {
                    let choiceDateTime = new Date(this.choiceDate0).getTime();
                    const minTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() - 1) + 24 * 60 * 60 * 1000;
                    const maxTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() + 1) - 24 * 60 * 60 * 1000;
                    const min = minTime;
                    const newDate = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
                    const max = newDate <= maxTime ? newDate : maxTime;
                    //如果已经选中一个日期 则 返回 该日期前后一个月时间可选
                    if (this.choiceDate0) {
                        return time.getTime() < min || time.getTime() > max;
                    }
                    //若一个日期也没选中 则 返回 当前日期以前日期可选
                    return time.getTime() > newDate;
                },
            },
            buttonLoading: false,
            isExpansion: false,

            classStyle: null,
            config: {},
            header: [],
            timer: null,
            key: 0,
            realData: [],
            loading: false,
        };
    },

    mounted() {
        // this.initBarEquipment()
        // this.initPieEquipment()
        this.getbuildingList();
        this.getenergyClassification();
        this.getPageList();
        this.getPageCharts();
        this.detail.style.data = [];
    },
    methods: {
        search() {
            if (this.searchData.date && this.searchData.date.length > 0) {
                const isPass = this.jumpDates();
                if (!isPass) {
                    return false;
                }
            }
            this.buttonLoading = true;
            this.searchData.pageNum = 1;
            this.getPageList(), this.getPageCharts();
        },
        resetFields() {
            this.workShopList = [];
            this.floorList = [];
            this.deviceList = [];
            this.searchData = {
                buildingId: '',
                workshopIds: null,
                deviceIds: null,
                classifyId: '',
                deviceName: '',
                //type: 1,
                date: [],
                dateType: 1,
                pageSize: 10,
                pageNum: 1,
            };
            this.search();
        },
        sizeChange(val) {
            this.searchData.pageSize = val;
            this.getPageList();
        },
        currentChange(val) {
            this.searchData.pageNum = val;
            this.getPageList();
        },
        /** 收起展开操作按钮操作 */
        changeExpansion() {
            this.isExpansion = !this.isExpansion;
        },
        getPageList() {
            const objs = {
                buildingId: this.searchData.buildingId,
                workshopIds: this.searchData.workshopIds,
                floor: this.searchData.floor,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date ? this.searchData.date[0] : '',
                end: this.searchData.date ? this.searchData.date[1] : '',
                timeType: this.searchData.type,
                dateType: this.searchData.dateType,
                pageSize: this.searchData.pageSize,
                pageNum: this.searchData.pageNum,
                guid: this.$store.state.app.guid ? this.$store.state.app.guid : this.$route.query.guid,
            };
            // const objss = {
            //   equipmentEnergyParam: objs
            // }
            console.log(this.$store.state.app.guid ? this.$store.state.app.guid : this.$route.query.guid, '@@');
            this.searchData.guid = this.$store.state.app.guid ? this.$store.state.app.guid : this.$route.query.guid;
            equipentEnergyList(objs).then((res) => {
                console.log(res, '@@@');
                this.setTableData = res.data.list;
                this.pageTotal = res.data.total || 0;
            });
        },

        getPageCharts() {
            this.chartsLoading = true;
            const objs = {
                buildingId: this.searchData.buildingId,
                floor: this.searchData.floor,
                workshopIds: this.searchData.workshopIds,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date ? this.searchData.date[0] : '',
                end: this.searchData.date ? this.searchData.date[1] : '',
                timeType: this.searchData.type,
                dateType: this.searchData.dateType,
                pageSize: this.searchData.pageSize,
                pageNum: this.searchData.pageNum,
                type: this.searchData.type,
                energyType: this.searchData.energyType,
                guid: this.$store.state.app.guid ? this.$store.state.app.guid : this.$route.query.guid,
            };
            equipentEnergyCharts(objs).then((res) => {
                console.log(res.data, '图表数据');
                if (JSON.stringify(res.data) === '{}') {
                    this.barEquipentX = [];
                    this.pieEquipentL = [];
                    this.pieEquipentY = [];
                    this.barEquipentY = [
                        {
                            name: '总费用',
                            type: 'line',
                            data: [],
                            showSymbol: false,
                            smooth: true,
                            areaStyle: {
                                opacity: 0.2,
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    {
                                        offset: 1,
                                        color: 'rgba(51, 153, 255, 0.20)',
                                    },
                                    {
                                        offset: 0,
                                        color: 'rgba(51, 153, 255, 1)',
                                    },
                                ]),
                            },
                        },
                    ];
                    this.initBarEquipment();
                    //this.initPieEquipment()
                    this.chartsLoading = false;
                    this.buttonLoading = false;
                    return;
                }
                console.log(res, '图表数据3333');
                const chartsData = res.data;
                this.barEquipentX = Object.keys(chartsData.brokenLine).sort();
                this.pieEquipentL = Object.keys(chartsData.pieGraph).sort();
                this.barEquipentY = [];
                this.pieEquipentY = [];
                const arr = [];
                this.pieEquipentL.map((item) => {
                    let totalNum = chartsData.pieGraph[item] || 0;
                    const obj = {
                        name: item,
                        value: totalNum,
                    };
                    this.pieEquipentY.push(obj);
                });
                this.barEquipentX.map((item) => {
                    let totalNum = this.searchData.energyType ? chartsData.brokenLine[item][this.searchData.energyType] || 0 : chartsData.brokenLine[item].equipmentConPrice;
                    arr.push(totalNum);
                });
                this.barEquipentY = [
                    {
                        name: '总费用',
                        type: 'line',
                        data: arr,
                        showSymbol: false,
                        smooth: true,
                        areaStyle: {
                            opacity: 0.2,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 1,
                                    color: 'rgba(51, 153, 255, 0.20)',
                                },
                                {
                                    offset: 0,
                                    color: 'rgba(51, 153, 255, 1)',
                                },
                            ]),
                        },
                    },
                ];
                this.initBarEquipment();
                //this.initPieEquipment()
                this.chartsLoading = false;
                this.buttonLoading = false;
            });
        },
        getenergyClassification() {
            energyClassification().then((res) => {
                this.classifyList = res.data;
            });
        },
        getEquipmentEchart() {},
        initBarEquipment() {
            const myEcharts = echarts.init(this.$refs.bar_chart_equipment);
            myEcharts.setOption(
                {
                    color: ['#3399FF'],
                    backgroundColor: '#fff',
                    tooltip: {
                        trigger: 'item',
                        formatter: ' {b} : {a} : {c}',
                    },
                    grid: {
                        left: '0%',
                        right: '2%',
                        bottom: '2%',
                        top: '4%',
                        containLabel: true,
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: this.barEquipentX,
                            axisTick: {
                                alignWithLabel: true,
                            },
                            axisLabel: {
                                textStyle: {
                                    color: '#606266',
                                    fontSize: '12px',
                                },
                            },
                        },
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            splitLine: {
                                show: false,
                            },
                            axisLabel: {
                                formatter: '{value}',
                                textStyle: {
                                    color: '#606266',
                                    fontSize: '12px',
                                },
                            },
                        },
                    ],
                    series: this.barEquipentY,
                },
                true
            );
        },
        getbuildingList() {
            getbuildingList().then((res) => {
                this.buildList = res.data || [];
            });
        },
        getFloorList(val) {
            const obj = {
                buildId: val,
            };
            getFloorList(obj).then((res) => {
                console.log(res, '楼层列表');
                this.floorList = res.data || [];
            });
        },
        getWorkShopList(val) {
            const obj = {
                buildingId: val,
            };
            getWorkShopList(obj).then((res) => {
                console.log(res.data, '3333');
                this.workShopList = res.data || [];
            });
        },
        getEquipentList(val) {
            getEquipentList(val).then((res) => {
                this.deviceList = res.data;
                console.log(res, '设备数据');
            });
        },
        buildChange(val) {
            this.workShopList = [];
            this.deviceList = [];
            this.floorList = [];
            this.searchData.floor = null;
            this.searchData.workshopIds = [];
            this.searchData.deviceIds = [];
            if (val) {
                this.getFloorList(val);
            }
        },
        floorChange(val) {
            console.log(val, '变化数据');
            this.workShopList = [];
            this.deviceList = [];
            this.searchData.workshopIds = [];
            this.searchData.deviceIds = [];
            if (val) {
                this.getWorkShopList(val);
            }
        },
        workShopChange(val) {
            console.log(val, '3333');
            this.deviceList = [];
            this.searchData.deviceIds = [];
            const arr = [];
            val.map((item) => {
                const obj = {
                    id: item,
                };
                arr.push(obj);
            });
            if (val) {
                this.getEquipentList(arr);
            }
        },
        headerClick(val) {
            if (val.property != 'deviceName' && val.property != 'createdDate') {
                this.searchData.energyType = val.property;
                this.getPageCharts();
            }
        },
        handleExport() {
            this.buttonLoading = true;
            var datas = {
                buildingId: this.searchData.buildingId,
                workshopIds: this.searchData.workshopIds,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date ? this.searchData.date[0] : '',
                end: this.searchData.date ? this.searchData.date[1] : '',
                timeType: this.searchData.type,
                pageSize: '',
                pageNum: '',
            };
            const obj = JSON.parse(JSON.stringify(datas));
            // exportEquipent(obj).then(res=> {
            //   const fileName = '设备能源监控记录.xlsx'
            //   saveExcel(res.data, fileName)
            // })
            this.download(
                'energy/monitoring/equipmentByReport',
                {
                    ...obj,
                },
                '设备能源监控记录.xlsx'
            );
            this.buttonLoading = false;
        },
        dateChange() {
            if (this.searchData.date && this.searchData.date.length > 0) {
                if (this.searchData.date[0] == this.searchData.date[1]) {
                    this.searchData.type = 2;
                } else {
                    this.searchData.type = 1;
                }
                this.jumpDates();
            } else {
                this.searchData.type = 1;
            }
        },
        dateTypeChange() {
            this.searchData.date = [];
        },
        jumpDates() {
            if (this.searchData.date[0] == this.searchData.date[1]) {
                if (this.searchData.dateType != 1) {
                    this.$message({
                        message: '选择时间和时间维度规则不匹配',
                        type: 'warning',
                    });
                    this.searchData.date = [];
                    return false;
                }
            } else {
                if (this.searchData.dateType == 1) {
                    this.$message({
                        message: '选择时间和时间维度规则不匹配',
                        type: 'warning',
                    });
                    this.searchData.date = [];
                    console.log(this.searchData.date, '数据332211');
                    return false;
                }
            }
            return true;
        },

        //格式化时间
        leaveTime(value) {
            return value;
            // return moment(value).format('HH:mm');
        },
        /*getList(){
            let query={
                ztGuid:this.$store.state.app.guid? this.$store.state.app.guid: this.$route.query.guid,
                //headListStr:this.headerChange.join(";"),
            }
            //this.loading=true;
          let url="/zutai/bDeviceHistory/getRealDataList"
            request({
            url:url,
            method:"get",
            params: query,

            }).then((res)=>{
                // console.log("实时数据",res.data);
                let sdata=[];
                res.data.forEach(element => {
                    let mdata=[element.reportTime,element.paramName,element.paramValue]
                    sdata.push(mdata)
                });
                this.realData=sdata;
                this.key=new Date().getTime();
                //this.loading=false;
            })
        },*/
    },
    beforeDestroy() {
        clearInterval(this.timer);
        this.timer = null;
    },
};
</script>

<style lang="scss" scoped>
@import '~@/assets/styles/element-variables.scss';

.common_page {
    background-color: #ffffff;
    height: 100%;
    width: 100%;
}
.main_content {
    padding: 6px;
}
.page_content {
    padding: 0 20px;
    .page_content_head {
        display: flex;
        padding: 16px;
        .right_echat {
            height: 246px;
            width: 460px;
            padding-left: 20px;
            border-left: 1px solid rgba(0, 0, 0, 0.08);
        }
        .left_echat {
            flex: 1;
        }
    }
}
::v-deep.sys_table {
    .tableHeaderRow {
        cursor: pointer;
        .tableHeaderCell:active {
            opacity: 0.6;
        }
        .tableHeaderCell:last-of-type:active {
            opacity: 1;
        }
        .tableHeaderCell:first-of-type:active {
            opacity: 1;
        }
        .tableHeaderCell:last-of-type {
            cursor: default;
        }
        .tableHeaderCell:first-of-type {
            cursor: default;
        }
    }
}

::v-deep.el-radio-group {
    .el-radio-button {
        .el-radio-button__inner {
            padding: 10px 12px;
            color: #666666;
            font-size: 14px;
        }
    }
    .is-active {
        .el-radio-button__inner {
            background: #fff;
            color: $--color-primary;
        }
    }
}
::v-deep.el-form {
    .el-form-item {
        .el-form-item__content {
            line-height: 32px;
        }
    }
}
</style>
